<template>
  <div class="shopping">
    <v-header title="我的购物车" ref="header">
      <div slot="right" class="headerRight" style="top: 2px; right: 5px;">
        <span v-if="editAndComplete" @click="handleEdit">编辑</span>
        <span v-else @click="handleComplete">完成</span>
      </div>
    </v-header>
    <scroll ref="scroll" style="overflow: hidden;" :style="{height: scrollHeight + 'px'}" :data="shoppingList" :pullDownRefresh="true" :pullUpLoad="false" @pullingDown="onPullingDown">
      <div class="goods-box">
        <!-- 商品类型 -->
        <p class="goods-type">
          <i class="icon iconfont icon-specialty"></i>特产
        </p>
        <ul class="goods-list">
          <li v-for="item in shoppingList" :key="item.id">
            <div class="checker" @click="item.selected = !item.selected">
              <i class="icon iconfont" :class="item.selected ? 'icon-box-selected' : 'icon-box-normal'"></i>
            </div>
            <div class="thumb" v-lazy:backgroundImage="item.thumbUrl" @click="handleSpecialtyDesc(item.goodsId)"></div>
            <div class="goods-info">
              <p class="goods-name" @click="handleSpecialtyDesc(item.goodsId)">{{item.goodsName}}</p>
              <div class="bottom">
                <p class="price">¥<span>{{null == item.discount || item.discount === 0 ? item.normalPrice : item.discountPrice}}</span></p>
                <inline-x-number width="35px" :min="1" v-model="item.goodsNum" :max="999" @on-change="changeShoppingNum(item)"></inline-x-number>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </scroll>
    <not-data v-if="shoppingList.length === 0" tip="购物车空空如也~<br>点击刷新" @handleClick="handleGetShopping"></not-data>
    <div class="goShoppingWrapper" @click.stop="handleGoShopping" v-if="shoppingList.length === 0">
      <p>去逛逛</p>
    </div>
    <!-- 底部购物车菜单 -->
    <div class="bottomDiv" ref="bottomWrapper">
      <div class="checker" @click="handleAllSelected">
        <i class="icon iconfont" :class="allSelectedOne ? 'icon-box-selected' : 'icon-box-normal'"></i>
        <span>全选</span>
      </div>
      <p class="price-wrapper" v-show="editAndComplete">合计：
        <span>¥ <span class="price">{{totalMoney}}</span></span>
      </p>
      <p class="submit-btn" v-show="editAndComplete" @click="handleGoSubmitOrder">
        结算({{total}})
      </p>
      <p class="delete-btn" v-show="!editAndComplete" @click="handleDeleteShopping" :class="{'active-delete': hasSelected}">删除</p>
    </div>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import axios from '@/api/axiosApi'
import Scroll from '@/components/scroll/scroll'
import { localUser } from '@/assets/js/local'
import { Badge, InlineXNumber } from 'vux'
import { mapMutations } from 'vuex'
import { handleBackMixin } from '@/assets/js/mixin'
import notData from '@/components/not-data/not-data'
import specialtyImage from '@/assets/img/myhome/specialty.png'
export default {
  mixins: [handleBackMixin],
  data() {
    return {
      specialtyImage: specialtyImage,
      editAndComplete: true,
      scrollHeight: '500px',
      imgUrl: 'http://p0w4yb0aj.bkt.clouddn.com/background_my.jpg',
      shoppingList: [],
      allSelectedOne: false,
      shoppingCount: 0,
      changeShoppingNumTemp: 0,
      invoice: {
        invoiceType: 0,
        invoiceRiseType: 0,
        invoiceContentType: 0,
        companyName: '',
        registrationNumber: '',
        accountPhone: '',
        accountEmail: ''
      },
      btnColor: '#E0E0E0',
      borderColor: '#E0E0E0',
      allPopupModels: []
    }
  },
  mounted() {
    this.scrollHeight =
      window.innerHeight - this.$refs.header.$el.offsetHeight - 60
  },
  computed: {
    total() {
      let count = 0
      this.shoppingList.forEach(item => {
        if (item.selected) {
          count += item.goodsNum
        }
      })
      this.shoppingCount = count
      return count
    },
    totalMoney() {
      let count = 0
      this.shoppingList.forEach(item => {
        if (item.selected) {
          // 判断是否打折
          if (item.discount === 0 || undefined === item.discount) {
            count += item.goodsNum * item.normalPrice
          } else {
            count += item.goodsNum * item.discountPrice
          }
        }
      })
      return count.toFixed(2)
    },
    // 作按钮变色
    hasSelected() {
      for (let i = 0; i < this.shoppingList.length; i++) {
        if (this.shoppingList[i].selected) {
          return true
        }
      }
      return false
    }
  },
  created() {
    this.pageNum = 1
    this.editAndComplete = true
    this.handleGetShopping()
  },
  activated() {
    this.handleGetShopping()
  },
  methods: {
    // 获取我的购物车数据
    handleGetShopping() {
      axios.get(
        this,
        '/v1/shoppingCart/' + localUser.get('id'),
        { pageNum: this.pageNum },
        data => {
          if (data.length === 0) {
            if (this.pageNum === 1) {
              this.$refs.scroll.hiddenPullDown()
            } else {
              this.pageNum--
              this.$refs.scroll.hiddenPullUpLoad()
            }
          } else {
            data = data.filter(item => item.goodsType === 201)
            data.forEach(item => {
              item.selected = false
              // 分组。暂时只有特产
              // if (item.goodsType === 101) {
              //   item.goodsTypeName = '酒店'
              // } else if (item.goodsType === 102) {
              //   item.goodsTypeName = '景区'
              // } else if (item.goodsType === 201) {
              //   item.goodsTypeName = '特产'
              // }
            })
            if (this.pageNum > 1) {
              this.shoppingList = this.shoppingList.concat(data)
            } else {
              this.shoppingList = data
            }
          }
        }
      )
    },
    handleEdit() {
      this.editAndComplete = false
    },
    handleComplete() {
      this.editAndComplete = true
    },
    handleGoSubmitOrder() {
      if (this.shoppingCount === 0) {
        this.$vux.toast.text('你还没有选择商品哟', 'middle')
        return
      } else {
        sessionStorage.setItem('shoppingCount', this.shoppingCount)
      }
      let shoppingTemp = []
      let ids = ''
      this.shoppingList.forEach(item => {
        if (item.selected) {
          item.goodsPrice = item.normalPrice
          shoppingTemp.push(item)
          ids += item.id + ','
        }
      })
      sessionStorage.setItem('selectedIds', ids)
      // 结算时候删除已经选择的订单
      // axios.delete(_self, '/v1/shoppingCart/' + ids.join(','), null, (data) => {
      //   ids.forEach(i => {
      //     const idx = _self.shoppingList.findIndex(o => o.id === i)
      //     if (idx > -1) {
      //       _self.shoppingList.splice(idx, 1)
      //     }
      //   })
      // })
      // vux存已经选择的数据
      this.setShoppingList(shoppingTemp)
      this.setInvoice(this.invoice)
      this.$router.push('/user/submitorder')
    },
    handleAllSelected() {
      this.allSelectedOne = !this.allSelectedOne
      if (this.allSelectedOne) this.hasSelected = true
      this.shoppingList.forEach(item => {
        item.selected = this.allSelectedOne
      })
    },
    handleDeleteShopping() {
      let count = 0
      let ids = []
      this.shoppingList.forEach(item => {
        if (item.selected) {
          ids.push(item.id)
          count++
        }
      })
      if (count === 0) {
        this.$vux.toast.text('你未选择任何商品哟', 'middle')
        return
      }
      const _self = this // 需要注意 onCancel 和 onConfirm 的 this 指向
      _self.$vux.confirm.show({
        title: '温馨提示',
        content: '你确定删除' + count + '件商品吗？',
        onConfirm() {
          axios.delete(
            _self,
            '/v1/shoppingCart/' + ids.join(','),
            null,
            data => {
              ids.forEach(i => {
                const idx = _self.shoppingList.findIndex(o => o.id === i)
                if (idx > -1) {
                  _self.shoppingList.splice(idx, 1)
                }
              })
              _self.allSelectedOne = false
            }
          )
        }
      })
    },
    onPullingDown() {
      this.pageNum = 1
      this.handleGetShopping()
    },
    handleSpecialtyDesc(goodsId) {
      this.$router.push('/specialLocalProductDetail/' + goodsId)
    },
    // 更新购物车数量
    changeShoppingNum(element) {
      axios.put(
        this,
        '/v1/shoppingCart/' + element.id,
        { goodsNum: element.goodsNum },
        res => {}
      )
    },
    // 阻止点击假事件
    stopCase() {},
    handleGoShopping() {
      this.$router.replace('/cart')
    },
    ...mapMutations({
      setShoppingList: 'SET_SHOPPING_LIST',
      setInvoice: 'SET_INVOICE'
    })
  },
  components: {
    VHeader,
    Scroll,
    Badge,
    InlineXNumber,
    notData
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.shopping
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  background-color $color-background
  z-index 101
.checker
  font-size 14px
  color #333
  extend-click()
  i
    font-size 24px
    color #e2e2e2
  .icon-box-selected
    color $color-theme
.goods-box
  background #fff
  margin-bottom 12px
.goods-type
  font-size 16px
  color #333
  border-bottom 1px solid #e2e2e2
  height 48px
  line-height 48px
  padding 0 16px
  i
    color $color-theme
    margin-right 12px
    font-size 18px
.goods-list
  padding 0 16px
  li
    padding 16px 0
    border-bottom 0.5px solid #e2e2e2
    display flex
    align-items center
    &:last-child
      border-bottom none
    .thumb
      min-width 90px
      width 90px
      height 90px
      background-size cover
      background-position center
      border-radius 2px
      margin 0 12px
    .goods-info
      position relative
      width calc(100% - 138px)
      height 90px
    .goods-name
      width 100%
      line-height 1.4
      font-size 14px
      color #333
      no-wrap-n(2)
    .bottom
      width 100%
      position absolute
      bottom 0
      display flex
      justify-content space-between
    .price
      color $color-theme
      font-size 12px
      span
        font-size 20px
.bottomDiv
  z-index 999
  background-color white
  display flex
  align-items center
  justify-content space-between
  width 100%
  height 60px
  position absolute
  bottom 0px
  border-top 1px solid #e2e2e2
  .checker
    margin-left 16px
    i
      transform translateY(3px)
      display inline-block
      margin-right 2px
  .price-wrapper
    font-size 15px
    color #333
    width calc(100% - 240px)
    text-align right
    span
      color $color-theme
    .price
      font-size 20px
  .submit-btn
    background $color-theme
    color #fff
    font-size 17px
    width 140px
    min-width 140px
    height 60px
    line-height 60px
    text-align center
  .delete-btn
    height 30px
    line-height 30px
    padding 0 15px
    border 1px solid #e2e2e2
    border-radius 3px
    margin-right 16px
    color #999
  .active-delete
    color $color-theme
    border-color $color-theme
    background #e9f2f1
.goShoppingWrapper
  margin-top 3px
  text-align center
  color #999
</style>

